//
//  ST_VoiceGroupGiftController.swift
//  ST_VoiceGroupGiftController
//
//  Created by Jason on 2021/8/26.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MBProgressHUD
import NIMSDK
import SwiftyAttributes
import SwiftyUserDefaults
import RxCocoa
import RxSwift

class ST_VoiceGroupGiftController: UIViewController,ST_TIANPaymentTransactionStateDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        layout_u_i()
        
        binding()
    }
    
    fileprivate func layout_u_i(){
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            make.height.equalTo(gift_container_height+58+71+16+BTSafeAreaBottom+83)
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(crowdView)
        crowdView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(100)
        }
        
        
        root_view.addSubview(segment_control)
        segment_control.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(crowdView.snp.bottom)
            make.height.equalTo(ST_GitSegmentControl.height)
        }
        
        //        segment_control.backgroundColor = .random
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(segment_control.snp.bottom).offset(5)
            make.height.equalTo(gift_container_height+10)
        }
        
        root_view.addSubview(pageControl)
        
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(1)
            make.height.equalTo(5+10)
            //            make.width.equalTo(100)
        }
        
        
        root_view.addSubview(giveBtn)
        root_view.addSubview(recharge_btn)
        giveBtn.snp.makeConstraints { (make) in
            make.width.equalTo(78)
            make.height.equalTo(34)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-10-16)
            make.right.equalToSuperview().offset(-15)
        }
        
        recharge_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(giveBtn)
            make.left.equalToSuperview().offset(15)
        }
        
        root_view.addSubview(number_options_button)
        number_options_button.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(26)
            make.centerY.equalTo(segment_control)
        }
        
        
        if let m = SC.numberOptions.last{
            selected_number = m
        }
        
        
        
        create_supplement_container_view()
        
        segment_control.titleArray = ["送礼物"]
        
    }
    
    
    fileprivate func create_supplement_container_view(){
        
        self.view.addSubview(supplement_container_view)
        supplement_container_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(155)
            make.bottom.equalTo(root_view.snp.top).offset( iPhoneXSeries ? -40 : -20)
            make.centerX.equalToSuperview()
        }
        
        supplement_container_view.addSubview(icon)
        icon.snp.makeConstraints { (make) in
            make.width.height.equalTo(115)
            make.center.equalToSuperview()
        }
        
        supplement_container_view.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
    
    var disposeBag = DisposeBag()
    
    fileprivate func binding(){
        
        viewModel.fetchGiftListSession(ignoreBlindBox: true).withUnretained(self).subscribe(onNext: { own,result in
            
            switch result {
            case .success:
                
                own.last_selected_control_model = own.viewModel.selectFirstOnlyGift()
                
                own.collectionView.reloadData()
                
                if let first = own.viewModel.onlyGiftArray.first{
                    own.pageControl.numberOfPages = first.pages
                    own.pageControl.currentPage = 0
                    
                    own.pageControl.isHidden = own.pageControl.numberOfPages < 2
                }
                
            case .failure(let err):
                own.toast(text: err.e)
            }
            
        }).disposed(by: disposeBag)
        
        
        segment_control.selected_closure = {[weak self] idx in
            
            guard let indexPath = self?.viewModel.indexPathOf(tabIndex: idx) else{
                return
            }
            
            self?.collectionView.setContentOffset(CGPoint.init(x: ScreenWidth*indexPath.row.cgFloat, y: -10), animated: true)
            
            guard let currItemModel = self?.viewModel.onlyGiftArray[safe:indexPath.row] else{
                return
            }
            
            self?.recharge_btn.isHidden = currItemModel.indexOfTab == 2
            self?.pageControl.numberOfPages = currItemModel.pages
            self?.pageControl.currentPage = 0
            self?.pageControl.isHidden = currItemModel.pages < 2
            
        }
    }
    
    
    //    MARK:- properties
    fileprivate lazy var icon:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 115/2.0
        control.imageView?.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
        return control
    }()
    
    fileprivate lazy var supplement_container_view:UIView = {
        let control = UIImageView()
        control.alpha = 0
        return control
    }()
    
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hex: 0x202223)
        control.cornerRadius = 16
        return control
    }()
    
    fileprivate lazy var close_view:UIButton = {
        let control = UIButton()
        control.addTarget(self, action: #selector(closeHanlde), for: UIControl.Event.touchUpInside)
        return control
    }()
    @objc fileprivate func closeHanlde(){
        
        last_selected_control_model?.isSelected = false
        
        self.goback_previous_controller()
    }
    
    
    fileprivate lazy var crowdView:ST_GiveGiftCrowdView = {
        let control = ST_GiveGiftCrowdView()
        control.data_array = userList
        return control
    }()
    
    fileprivate lazy var segment_control:ST_GitSegmentControl = {
        let control = ST_GitSegmentControl()
        //        control.backgroundColor = .random
        return control
    }()
    
    
    
    fileprivate var selected_number:ST_GiftNumberStruct?{
        didSet{
            
            GIFT_NUMBER = selected_number?.number ?? 1
            
            if let m = selected_number{
                let str = m.number.string + "个"
                number_options_button.setTitle(str.withAttributes([Attribute.font(.systemFont(ofSize: 12, weight: .medium)),.textColor(#colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 1))]), for: .normal)
                
            }
        }
    }
    
    fileprivate lazy var number_options_button:ST_TianButton = {
        let control = ST_TianButton(style: ST_TianButtonStyle.title_left_image_right(titleLeft: 5, imageSize: CGSize(width: 12, height: 12), layout: ST_TianButtonLayoutModel.inside_auto_resize(relevantOffset: 12, lastControlEdgeValue: -5)))
        control.cornerRadius = 5
        control.borderColor = #colorLiteral(red: 1, green: 0.7970786095, blue: 0, alpha: 1)
        control.borderWidth = 1
        control.setImage(ST_ImageUtils.imageName("arrow_icon_up"), for: UIControl.State.selected)
        control.setImage(ST_ImageUtils.imageName("arrow_icon_down"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(pick_number_handle), for: .touchUpInside)
        return control
    }()
    
    fileprivate lazy var gift_container_height = ST_GiftItemView.height*2+ST_GiftItemView.gap
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.scrollDirection = .horizontal
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.itemSize = CGSize.init(width: ScreenWidth, height: gift_container_height)
        return controlLayout
    }()
    
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.isPagingEnabled = true
        control.backgroundColor = Color.clear
        control.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
        //        control.backgroundColor = .random
        control.delegate = self
        control.dataSource = self
        //        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_GiftTabCell.self)
        control.register(cellWithClass: ST_GiftMemberTabCell.self)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    fileprivate weak var last_selected_control_model:ST_BTGiftModel?{
        didSet{
            
            guard let m = last_selected_control_model else{
                self.supplement_container_view.alpha = 0
                return
            }
            
            self.number_options_button.alpha = m.tabType == .gift ? 1 : 0
            
            if m.tabType == .sweetGuard{
                
                self.supplement_container_view.alpha = 1
                
                self.icon_supplement_image_view.pin_setImage(from: m.imageUrl.url)
                
            }else{
                self.supplement_container_view.alpha = 0
            }
            
        }
    }
    
    fileprivate lazy var viewModel = ST_GiftViewModel()
    
    
    fileprivate lazy var pageControl:UIPageControl = {
        let control = UIPageControl()
        control.pageIndicatorTintColor = UIColor.init(hex: 0xACB4C0)
        control.currentPageIndicatorTintColor = UIColor.init(hex: 0xFEC207)
        //        control.addTarget(self, action: #selector(changePage(sender:)
        //            ), for: UIControl.Event.touchUpInside)
        control.isUserInteractionEnabled = false
        
        //        control.backgroundColor = .random
        return control
    }()
    
    fileprivate lazy var giveBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("赠送")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.setTitleColorForAllStates(UIColor.init(hex: 0x202223)!)
        control.cornerRadius = 17
        control.addTarget(self, action: #selector(give_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var recharge_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleForAllStates("马上充值")
        control.setTitleColorForAllStates(Color.init(hexString: "#FEC207")!)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_下一页_orange")!)
        
        control.semanticContentAttribute = .forceRightToLeft
        control.addTarget(self, action: #selector(recharge_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var give_member:BTMemberGoodsModel?
    
    var present_goods_closure:((ST_BTIMGiftMessageModel)->())?
    
    var userList = [ST_GiveGiftCrowdCellModel]()
    
    var roomId = ""
    
    fileprivate var prepare_present_list = [String]()
    
    fileprivate var lastPage = 0
}

extension ST_VoiceGroupGiftController{
    
    
    
    @objc fileprivate func pick_number_handle(){
        
        if number_options_button.isSelected {return}
        
        let vc = ST_GiftNumbersController.createController()
        self.addChild(vc)
        view.addSubview(vc.view)
        vc.view.snp.makeConstraints { make in
            make.top.equalTo(number_options_button.snp.bottom).offset(10)
            make.right.equalTo(number_options_button)
            make.width.equalTo(110)
            make.height.equalTo(226)
        }
        
        vc.callBack = {[weak self] m in
            
            guard let strongSelf = self else { return  }
            
            vc.view.removeFromSuperview()
            vc.removeFromParent()
            
            self?.selected_number = m
            strongSelf.number_options_button.isSelected = false
        }
        
        number_options_button.isSelected = true
    }
    
    @objc fileprivate func infoHandle(){
        
        GlobalPresent(toController: ST_SweetRankViewController())
        
    }
    
    func transaction_succeed() {
        
        guard let memberModel = self.give_member else { return }
        
        let goods = ST_BTIMGiftMessageModel()
        
        goods.goodsId = memberModel.limited_time.string
        
        goods.title = "送了你\(memberModel.limited_time)个月会员"
        
        goods.type = ST_IMGoodsType.give_member
        
        goods.subTitle = "亲密度+"+memberModel.intimacy.string
        
        present_goods_closure?(goods)
        
        let vc = BTVerticalAlertViewController.createGiveMemberAlert()
        
        GlobalPresent(toController: vc)
    }
    
    @objc fileprivate func recharge_handle(){
        
        ST_RechargeViewController.toast()
        
    }
    
    @objc fileprivate func recharge_tips_handle(){
        
        
        //        let alert = BTVerticalAlertViewController.createRequireRechargeAlert()
        //
        //        alert.confirm_closure = {[weak self] in
        //
        //            self?.recharge_handle()
        //        }
        //
        //        GlobalPresent(toController: alert)
        
        
        ST_RechargeViewController.toast()
        
        self.hidden_indeterminate_h_u_d()
    }
    
    @objc fileprivate func give_handle(){
        
        prepare_present_list.removeAll()
        
        prepare_present_list = userList.filter({ $0.isSelected }).map({ $0.accid })
        
        guard prepare_present_list.count > 0 else{return}
        
        self.show_indeterminate_h_u_d()
        
        send_gift_task()
    }
    
    
    fileprivate func send_gift_task(){
        
        guard let model = last_selected_control_model,let goodsModel = model.common ,let coin = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin ,let sendToAccid = prepare_present_list.first else {
            
            self.toast(text: "送礼物，成功啦")
            
            return
        }
        
        var expendCoin = goodsModel.useCoin.float
        
        let giftNumber = self.selected_number?.number ?? 1
        
        expendCoin = expendCoin * giftNumber.float
        
        if coin < expendCoin{
            
            self.hidden_indeterminate_h_u_d()
            
            ST_MaidWayManager.shared.source = .送礼物
            
            recharge_tips_handle()
            
            return
        }
        
        JVrequest(PH.presentRoomGiftApi ,parameters: ["room_id":roomId,"target_accid":sendToAccid,"gift_id":goodsModel.id ?? "","num":giftNumber.string], success: { (json) in
            
            if self.prepare_present_list.count > 0{
                self.prepare_present_list.remove(at: 0)
            }
            
            
            
            main_thread_execute {
                ST_BTUserInfoManager.shared.modify_sweet_coin(value: coin - goodsModel.useCoin.float)
            }
            
            
            main_thread_execute(afterDelay: 1) {
                self.send_gift_task()
            }
            
            
            
        }) { (code, err) in
            
            self.hidden_indeterminate_h_u_d()
            
            if code == 10004{
                
                ST_RechargeViewController.toast()
                
            }else{
                
                self.toast(text: err)
            }
        }
        
    }
    @objc fileprivate func changePage(sender:UIPageControl){
        
        print("点击跳转页事件")
    }
    
    fileprivate func update_selected(item:ST_BTGiftModel){
        
        if item == last_selected_control_model{
            return
        }
        
        last_selected_control_model?.isSelected = false
        last_selected_control_model = item
        
        collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)
    }
    
    /// 滑动到下一页
    fileprivate func scrollTo(currPage:Int){
        
        guard currPage > -1,let m = viewModel.data_array[safe:currPage],lastPage != currPage else{
            return
        }
            
        lastPage = currPage
        
        if let firstItem = m.pageArray.first{
            m.pageArray.first?.isSelected = true
            self.update_selected(item: firstItem)
        }
        
        self.segment_control.selectBtn(index: m.indexOfTab)
        
        self.recharge_btn.isHidden = m.indexOfTab == 2
        self.pageControl.numberOfPages = m.pages
        self.pageControl.currentPage = m.currentPageOfTab
        self.pageControl.isHidden = self.pageControl.numberOfPages < 2
        
        
    }
    
}


extension ST_VoiceGroupGiftController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel.onlyGiftArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let model = viewModel.onlyGiftArray[indexPath.row]
        
        if let firstItem = model.pageArray.first,firstItem.tabType == .member{
            
            let cell = collectionView.dequeueReusableCell(withClass: ST_GiftMemberTabCell.self, for: indexPath)
            
            cell.selected_closure = {[weak self] model in
                
                self?.last_selected_control_model?.isSelected = false
                self?.last_selected_control_model = model
                self?.collectionView.reloadData()
            }
            
            cell.model = model
            
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_GiftTabCell.self, for: indexPath)
        
        cell.model = model
        
        cell.selected_closure = {[weak self] model in
            
            self?.last_selected_control_model?.isSelected = false
            self?.last_selected_control_model = model
            self?.collectionView.reloadData()
        }
        
        return cell
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        scrollviewdidEndScroll(scrollView)
        
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        
        let currPage = (scrollView.contentOffset.x/ScreenWidth).int
        
        scrollTo(currPage: currPage)
    }
    
    //    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        let currPage = (scrollView.contentOffset.x/ScreenWidth).int
        
        scrollTo(currPage: currPage)
        
    }
}


